import React, {useEffect, useState} from 'react';
import {
  View,
  Text,
  StatusBar,
  TextInput,
  StyleSheet,
  PixelRatio,
} from 'react-native';
import {windowWidth, windowHeight, getHeight, getWidth} from '@/utils/index';
import {PermissionsAndroid, Platform} from 'react-native';
import {init, Geolocation} from 'react-native-amap-geolocation';
import Touchable from '../../components/Touchable';
// 连接到dva,react-redux本身充当一个桥梁的作用
import {connect, ConnectedProps} from 'react-redux';
// 导入模块类型
import {RootState} from '@/models/index';
// 从users.ts这个model里面导入users的类型
import {IUserInfo} from '@/models/user';
import Toast from 'react-native-root-toast';
import AsyncStorage from '@react-native-async-storage/async-storage';
import LinearGradient from 'react-native-linear-gradient';
const mapStateToProps = ({users, loading}: RootState) => {
  return {
    userInfo: users?.userInfo,
    photographerInfoByName: users?.photographerInfoByName,
    // 在触发getUserInfo方法时加上加载效果
    loading: loading.effects['users/getUserInfo'],
  };
};
// connect接受一个mapStateToProps函数，将dva的state映射成当前组件的props
const connector = connect(mapStateToProps);
// 获取映射出来的props的类型，给IProps做定义
type ModelState = ConnectedProps<typeof connector>;
interface IProps extends ModelState {
  navigation: {navigate: any};
}

function Appointment(props: IProps) {
  const [nameValue, setNameValue] = useState('');
  const [users, setUsers] = useState<IUserInfo[]>();
  const {dispatch, userInfo, photographerInfoByName, navigation} = props;
  useEffect(() => {
    //  console.log("userInfo",userInfo);
    dispatch({
      type: 'users/getUserInfo',
      callback: (users: IUserInfo[]) => {
        setUsers(users);
      },
    });
  }, []);

  const handleSearch = () => {
    console.log('names', nameValue);
    if (nameValue.length === 0) {
      Toast.show('请先输入摄影师名称再搜索', {
        position: Toast.positions.CENTER,
        duration: Toast.durations.LONG,
        shadow: true,
        animation: true,
      });
      return;
    }
    dispatch({
      type: 'users/getPhotographerInfoByName',
      payload: {
        photographer_name: nameValue,
        callback: (photographerInfoList: IUserInfo) => {
          // 点击跳转摄影师列表页
          navigation.navigate('PhotographerList');
        },
      },
    });
  };
  const handlePlace = async() => {
    console.log('点击了获取定位');
    // 先登录才能通过地图查看附近的摄影师
    const token = await AsyncStorage.getItem('token');
    if(token){
       // 对于 Android 需要自行根据需要申请权限
       const grant = await PermissionsAndroid.requestMultiple([
        // 只需要允许一次后续都不会再弹窗
        PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION,
        PermissionsAndroid.PERMISSIONS.ACCESS_COARSE_LOCATION,
      ]);
      // {"android.permission.ACCESS_COARSE_LOCATION": "granted", "android.permission.ACCESS_FINE_LOCATION": "granted"}
      // {"android.permission.ACCESS_COARSE_LOCATION": "denied", "android.permission.ACCESS_FINE_LOCATION": "denied"}
      console.log("权限控制",grant);
      if(grant && Object.values(grant)[0] &&  Object.values(grant)[0] === "granted"){
        // 使用自己申请的高德 App Key 进行初始化
        await init({
        ios: '9bd6c82e77583020a73ef1af59d0c759',
        android: '5c6fa50e065b5c77d22e6162667c2b15',
        });
        navigation.navigate('Map');
        return;
      }
      console.log("没有权限打开地图")
    }else {
      Toast.show("请先登录再通过地图查看附近的摄影师", {
        position: Toast.positions.CENTER,
        duration: Toast.durations.LONG,
        shadow: true,
        animation: true,
      });
      navigation.navigate('Login');
    }
   
     
  };
  return (
    <View style={styles.appintment}>
      <LinearGradient colors={['#fff', '#A75E5E']} style={styles.linearGradient}>
      {/* 设置隐藏状态栏 hiddle={true} */}
      <StatusBar backgroundColor="#fff" barStyle="dark-content" />
      <View style={styles.search}>
        <TextInput
          placeholder="请输入摄影师名称进行搜索"
          style={styles.text_input}
          onChangeText={text => {
            console.log('text', text), setNameValue(text);
          }}
          value={nameValue}
        />
        <Touchable onPress={handleSearch}>
          <Text style={styles.btn}>搜索</Text>
        </Touchable>
      </View>
      <Touchable style={styles.place} onPress={handlePlace}>
        <Text style={styles.text}>点击获取定位</Text>
      </Touchable>
      </LinearGradient>
    </View>
  );
}
const styles = StyleSheet.create({
  appintment: {
    width: windowWidth,
    height: windowHeight,
    // backgroundColor:"#fff"
  },
  linearGradient: {
    // flex: 1,
    width:"100%",
    height:"100%",
    paddingLeft: 15,
    paddingRight: 15,
    borderRadius: 5,
    display: 'flex',
    flexDirection: 'column',
    alignItems: 'center',
    paddingTop: getWidth(30),
  },
  search: {
    display: 'flex',
    flexDirection: 'row',
    padding: 20,
    paddingBottom: 50,
  },
  text_input: {
    height: 40,
    width: getWidth(70),
    borderColor: '#A75E5E',
    borderWidth: 1 / PixelRatio.get(),
    borderRadius: 20,
    fontSize: 14,
    padding: 0,
    paddingLeft: 20,
    marginRight: 20,
    color: '#999',
  },
  btn: {
    width: getWidth(15),
    backgroundColor: '#A75E5E',
    color: '#fff',
    textAlign: 'center',
    borderRadius: 20,
    height: 40,
    lineHeight: 40,
  },
  place: {
    width: getWidth(40),
    height: getWidth(40),
    backgroundColor: '#A75E5E',
    borderRadius: getWidth(40),
    display: 'flex',
    justifyContent: 'center',
    alignItems: 'center',
  },
  text: {
    color: '#fff',
    fontSize: 18,
  },
});
export default connector(Appointment);
